<template>
  <div>
    <el-dialog
      title="填写课程信息"
      :visible.sync="visible"
      :close-on-click-modal="false"
      center
      :width="dialogWidth"
      @close="handleClose"
    >
      <el-form ref="courseForm" :model="form" label-width="120px" class="course-form-wrapper">
        <!-- 1. 上课学生选择 -->
        <el-form-item label="上课学生：">
          <el-input
            v-model="form.studentsText"
            placeholder="请选择上课学生"
            @click.native="handleSelectStudents"
          />
        </el-form-item>

        <!-- 2. 课程时长选择 -->
        <el-form-item label="课程时长：">
          <el-select
            v-model="form.selectedDurationId"
            placeholder="请选择课程时长"
            clearable
            class="duration-select"
            @change="handleDurationChange"
          >
            <el-option
              v-for="(item, index) in durationOptions"
              :key="index"
              :value="item.id"
              :label="item.name"
            >
              <span style="float: left">{{ item.name }}</span>
              <span class="time-badge">{{ item.duration }} 分钟</span>
            </el-option>
          </el-select>
          <div v-if="form.selectedDuration" class="duration-tip">
            本课程消耗 {{ form.selectedDuration.classHour }} 课时
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="medium"
          :disabled="!form.studentsText || !form.selectedDuration"
          @click="handleStartClass"
        >
          开始上课
        </el-button>
      </div>
    </el-dialog>
    <student-choose-dialog v-model="studentChooseDialogVisible" @on-select="selectStudent"/>
  </div>
</template>

<script>
import StudentChooseDialog from '@/views/student/components/studentChooseDialog.vue'
import { courseDurationTypeList } from '@/api/wordSystemCourseDurationType'
import { classSchedule } from '@/api/wordSystemCourse'

export default {
  name: 'CourseInfoDialog',
  components: { StudentChooseDialog },
  props: {
    visible: { type: Boolean, default: false },
    selectedMode: { type: String, default: '' },
    courseType: { type: String, default: '' }
  },
  data() {
    return {
      studentChooseDialogVisible: false,
      studentSelect: {},
      form: {
        studentsText: '',
        selectedDurationId: '',
        selectedDuration: null
      },
      durationOptions: []
    }
  },
  computed: {
    dialogWidth() {
      const screenWidth = window.innerWidth
      if (screenWidth < 768) return '90%'
      if (screenWidth < 1200) return '70%'
      return '600px'
    }
  },
  watch: {
    'form.selectedDurationId'(value) {
      this.form.selectedDuration = this.durationOptions.find(item => item.id === value)
    }
  },
  mounted() {
    this.loadDurationData()
  },
  methods: {
    async loadDurationData() {
      this.durationOptions = await courseDurationTypeList({})
    },
    handleSelectStudents() {
      this.studentChooseDialogVisible = true
    },
    handleDurationChange(value) {
    },
    async handleStartClass() {
      const time = new Date().getTime()
      const courseInfo = {
        courseDurationType: this.form.selectedDurationId,
        courseType: this.courseType,
        startTimeTimestamp: time,
        endTimeTimestamp: time + this.form.selectedDuration.duration * 60 * 1000,
        location: '线上 腾讯会议',
        notes: '临时课程（未排课）',
        stuId: this.studentSelect.id,
        teachingMode: this.selectedMode
      }
      const res = await classSchedule(courseInfo)
      if (res === '-1') {
        // 选择是否继续上课
        this.$confirm('此次课程时间与接下来的课程时间发生了冲突！是否继续上课？', '课程时间冲突提示', {
          confirmButtonText: '继续上课',
          cancelButtonText: '取消',
          showClose: false
        }).then(async() => {
          const res = await classSchedule({
            ...courseInfo,
            id: '123456'
          })
          window.open(
            `${window.location.origin}${window.location.pathname}#traditionalTeaching?q1=${res}`,
            '_blank',
            'width=600,height=800,top=100,left=200'
          )
        }).catch(() => {
        }).finally(() => {
          this.handleClose()
        })
      } else {
        this.handleClose()
        window.open(
          `${window.location.origin}${window.location.pathname}#traditionalTeaching?q1=${res}`,
          '_blank',
          'width=600,height=800,top=100,left=200'
        )
      }
    },
    handleClose() {
      this.form.studentsText = ''
      this.form.selectedDuration = null
      this.$emit('confirm')
    },
    selectStudent(student) {
      this.studentSelect = student
      this.form.studentsText = student.name
      this.studentChooseDialogVisible = false
    }
  }
}
</script>

<style scoped>
.course-form-wrapper {
  padding: 10px 0;
}

.student-select-input {
  cursor: pointer;
}

.duration-select {
  width: 100%;
}

.duration-tip {
  margin-top: 8px;
  line-height: 1.5;
  display: inline-block;
  padding: 3px 10px;
  background-color: #f0f7ff;
  color: #0084ff;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 15px 0;
  border-top: 1px solid #f5f7fa;
}

.time-badge {
  float: right;
  color: #0084ff;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

</style>
